/**
 * @desc
 *  生产环境webpack打包配置文件
 *  npm run dist
 * @使用场景
 *
 * @author  杨晓东[of1081]
 * @company qianmi.com
 * @Date    15/10/10
 **/
'use strict';
let path = require('path');

let webpack = require('webpack');
let ExtractTextPlugin = require("extract-text-webpack-plugin");
let basicConfigFactory =require('./webpack.config.factory')();
let webpackAfterBus =require('./webpack-after-bus');


let inquirerEnv = require('./inquire-env');
inquirerEnv().then(({envCode})=>{
	beginWebpack({envCode});
});

function beginWebpack({envCode}){
	let plugins  = [
		new webpack.DefinePlugin({
			'process.env.NODE_ENV': JSON.stringify(envCode==='prod'?'production':envCode),
			'XSite_ENV': JSON.stringify(envCode)
		}),
		new ExtractTextPlugin("[name]-[hash]-styles.css")
	];
	if(envCode === 'prod'){
		plugins.push(new webpack.optimize.OccurrenceOrderPlugin());
		plugins.push(new webpack.optimize.UglifyJsPlugin({
			compress: {
				warnings: false
			}
		}));
	}
	
	let output   ={
		path: './build',
		filename: 'bundle-[name]-[hash].js',
		chunkFilename:'chunk.[id].[name].[hash].js',
		publicPath: 'http://oss-hz.qianmi.com/x-site-admin/'+envCode+'/public/build/'
	}
	
	if(envCode === 'test' || envCode=== 'dev'){
		output = {
			path: './build',
			filename: 'bundle-[name].js',
			chunkFilename:'chunk.[id].[name].[hash].js',
			publicPath: '/build/'
		}
	}

	let productConfig =basicConfigFactory.buildConfig({
		entry: {
			"imgManager":"./assets/img-manager/app.js"
		},
		output,
		plugins
	});
	
	console.log('打包配置文件',JSON.stringify(productConfig));
	
	let compiler = webpack(productConfig);
	compiler.run(function(err, stats) {
		if(err){
			console.error(err);
		} else {
            if(stats.compilation.errors.length>0){
                console.log(stats.compilation.errors[0]);
                throw stats.compilation.errors[0];
            }
			webpackAfterBus({
				assetsByChunkName:stats.toJson().assetsByChunkName,
				envCode
			});
		}
	});
	
}
